public class Leetcode307NumArray {

    private int[] sum; // sum[i] 存储前 i 个元素的和，sum[0] = 0
    private int[] data;

    public Leetcode307NumArray(int[] nums) {
        data = new int[nums.length];
        for (int i = 0; i < nums.length; i ++) {
            data[i] = nums[i];
        }

        sum = new int[nums.length + 1];
        sum[0] = 0;
        for (int i = 1; i < sum.length; i ++) {
            sum[i] = sum[i - 1] + nums[i - 1];
        }
    }

    public int sumRange(int i, int j) {
        return sum[j + 1] - sum[i];
    }

    public void update(int i, int val) {
        data[i] = val;
        for (int index = i + 1; index < sum.length; index ++) {
            sum[index] = sum[index - 1] + data[index - 1];
        }
    }

    public static void main(String[] args) {
        int[] nums = {1, 3, 5};
        Leetcode307NumArray na = new Leetcode307NumArray(nums);
        System.out.println(na.sumRange(0, 2));
        na.update(1, 2);
        System.out.println(na.sumRange(0, 2));
    }

}
